#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
文件监控管理模块
"""

import os
import time
import threading
import asyncio
import queue
from typing import Dict, List, Callable, Optional
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from datetime import datetime

from database_manager import DatabaseManager
from order_parser import OrderParser
from config_manager import get_config


class OrderFileHandler(FileSystemEventHandler):
    """订单文件事件处理器"""
    
    def __init__(self, base_path: str, db_manager: DatabaseManager, 
                 order_parser: OrderParser, status_callback: Callable = None,
                 callback_queue: queue.Queue = None):
        self.base_path = base_path
        self.db_manager = db_manager
        self.order_parser = order_parser
        self.status_callback = status_callback
        self.callback_queue = callback_queue
    
    def on_any_event(self, event):
        """处理文件系统事件"""
        # 打印事件信息
        event_type = event.event_type
        file_path = event.src_path
        is_dir = event.is_directory
        
        print(f"📁 文件系统事件: {event_type} - {file_path} (目录: {is_dir})")
        
        # 处理目录事件（如创建新订单文件夹）
        if event.is_directory:
            print(f"📂 处理目录事件: {file_path}")
            # 检查是否是订单文件夹
            folder_name = os.path.basename(file_path)
            if self.order_parser.is_order_folder(folder_name):
                print(f"✅ 检测到新订单文件夹: {folder_name}")
                # 延迟处理目录事件
                def delayed_process_dir():
                    time.sleep(1)  # 延迟1秒
                    self._process_directory_change_sync(file_path, event_type)
                
                thread = threading.Thread(target=delayed_process_dir)
                thread.daemon = True
                thread.start()
            else:
                print(f"❌ 不是订单文件夹，忽略: {folder_name}")
            return
        
        # 处理文件事件
        filename = os.path.basename(file_path)

        # 忽略隐藏文件
        if filename.startswith('.'):
            print(f"⚠️ 忽略隐藏文件变化: {file_path}")
            return

        # 仅监控特定类型文件
        _, ext = os.path.splitext(filename)
        ext = ext.lower()
        allowed_extensions = {'.pdf', '.ai', '.cdr'}
        if ext not in allowed_extensions:
            print(f"⚠️ 忽略不在监控列表的文件: {file_path}")
            return

        def delayed_process():
            time.sleep(1)  # 延迟1秒
            self._process_file_change_sync(event.src_path, event_type)
        
        # 在单独线程中处理
        thread = threading.Thread(target=delayed_process)
        thread.daemon = True
        thread.start()
    
    def _process_file_change_sync(self, file_path: str, event_type: str = "modified"):
        """处理文件变化（同步版本）"""
        try:
            print(f"🔍 处理文件变化: {file_path} (事件类型: {event_type})")

            filename = os.path.basename(file_path)

            if filename.startswith('.'):
                print(f"⚠️ 忽略隐藏文件: {file_path}")
                return

            _, ext = os.path.splitext(filename)
            ext = ext.lower()
            allowed_extensions = {'.pdf', '.ai', '.cdr'}
            if ext not in allowed_extensions:
                print(f"⚠️ 忽略不在监控列表的文件: {file_path}")
                return
            
            # 解析订单路径
            relative_path = os.path.relpath(file_path, self.base_path)
            path_parts = relative_path.split(os.sep)
            
            print(f"📂 相对路径: {relative_path}")
            print(f"📋 路径部分: {path_parts}")
            
            if len(path_parts) >= 1:
                order_folder = path_parts[0]
                print(f"📁 订单文件夹: {order_folder}")
                
                if self.order_parser.is_order_folder(order_folder):
                    order_path = os.path.join(self.base_path, order_folder)
                    
                    # 检查订单文件夹是否还存在
                    if not os.path.exists(order_path):
                        print(f"🗑️ 订单文件夹已删除: {order_folder}")
                        # 处理订单删除逻辑
                        self._handle_order_deletion(order_folder, order_path)
                        return
                    
                    # 对于删除事件，如果订单文件夹还存在，说明只是文件被删除
                    if event_type == "deleted":
                        print(f"🗑️ 订单文件夹内文件被删除: {file_path}")
                        # 更新订单状态（因为文件数量可能发生变化）
                        self._update_order_status(order_folder, order_path, event_type)
                    else:
                        print(f"✅ 检测到订单文件夹变化: {order_folder}")
                        self._update_order_status(order_folder, order_path, event_type)
                else:
                    print(f"❌ 不是订单文件夹: {order_folder}")
            else:
                print(f"⚠️ 路径解析失败: {path_parts}")
                
        except Exception as e:
            print(f"❌ 处理文件变化错误: {e}")
            import traceback
            traceback.print_exc()
    
    def _process_directory_change_sync(self, dir_path: str, event_type: str = "created"):
        """处理目录变化（同步版本）"""
        try:
            print(f"🔍 处理目录变化: {dir_path} (事件类型: {event_type})")
            
            # 获取目录名
            folder_name = os.path.basename(dir_path)
            print(f"📁 目录名: {folder_name}")
            
            # 检查是否是订单文件夹
            if self.order_parser.is_order_folder(folder_name):
                print(f"✅ 确认是订单文件夹: {folder_name}")
                
                # 处理删除事件
                if event_type == "deleted":
                    print(f"🗑️ 订单文件夹已删除: {folder_name}")
                    self._handle_order_deletion(folder_name, dir_path)
                else:
                    # 处理创建、修改、移动事件
                    if os.path.exists(dir_path):
                        self._update_order_status(folder_name, dir_path, event_type)
                    else:
                        print(f"❌ 目录不存在: {dir_path}")
            else:
                print(f"❌ 不是订单文件夹: {folder_name}")
                
        except Exception as e:
            print(f"❌ 处理目录变化错误: {e}")
            import traceback
            traceback.print_exc()
    
    def _update_order_status(self, order_folder: str, order_path: str, event_type: str = "modified"):
        """更新订单状态"""
        try:
            print(f"🔄 开始更新订单状态: {order_folder}")
            
            # 解析订单信息
            order_info = self.order_parser.parse_order_info(order_folder)
            if not order_info:
                print(f"❌ 无法解析订单信息: {order_folder}")
                return
            
            number, customer = order_info['number'], order_info['customer']
            print(f"📋 订单信息: {number} - {customer}")
            
            # 检查订单是否存在
            order = self.db_manager.find_order_by_number(number)
            
            if not order:
                # 创建新订单
                order_data = {
                    'number': number,
                    'customer': customer,
                    'path': order_path
                }
                order = self.db_manager.create_order(order_data)
                print(f"🆕 创建新订单: {number} - {customer}")
            else:
                print(f"📝 找到现有订单: {number} - {customer}")
                
                # 更新现有订单的路径和客户信息
                update_data = {}
                if order['path'] != order_path:
                    update_data['path'] = order_path
                if order['customer'] != customer:
                    update_data['customer'] = customer
                
                if update_data:
                    self.db_manager.update_order(number, update_data)
                    print(f"🔄 更新订单信息: {number} - {customer}")
                    if 'path' in update_data:
                        print(f"  📁 路径已更新: {order_path}")
                    if 'customer' in update_data:
                        print(f"  👤 客户已更新: {customer}")
                    
                    # 发送订单信息更新通知
                    if self.callback_queue:
                        print(f"📡 发送订单信息更新通知: 订单编号 {number}")
                        self.callback_queue.put(('order_updated', number, update_data))
            
            # 自动创建状态文件夹（如果不存在）
            self.order_parser.create_status_folders(order_path)
            
            # 检查状态（实时计算，不存储到数据库）
            print(f"🔍 检查订单状态: {order_path}")
            status_data = self.order_parser.check_order_status(order_path)
            print(f"📊 状态数据: {status_data}")
            
            # 通知状态变化
            if self.callback_queue:
                print(f"📡 发送状态变化通知: 订单编号 {number}")
                # 将状态变化放入队列，由主线程处理
                self.callback_queue.put(('status_change', number, status_data))
            elif self.status_callback:
                print(f"📡 发送状态变化通知: 订单编号 {number}")
                # 使用线程安全的方式调用异步回调
                import asyncio
                import threading
                
                def call_async_callback():
                    try:
                        loop = asyncio.new_event_loop()
                        asyncio.set_event_loop(loop)
                        loop.run_until_complete(self.status_callback(number, status_data))
                        loop.close()
                    except Exception as e:
                        print(f"❌ 异步回调执行失败: {e}")
                
                # 在单独线程中执行异步回调
                thread = threading.Thread(target=call_async_callback)
                thread.daemon = True
                thread.start()
            else:
                print(f"⚠️ 没有设置状态回调函数")
            
        except Exception as e:
            print(f"❌ 更新订单状态错误: {e}")
            import traceback
            traceback.print_exc()
    
    def _handle_order_deletion(self, order_folder: str, order_path: str):
        """处理订单删除"""
        try:
            print(f"🗑️ 开始处理订单删除: {order_folder}")
            
            # 解析订单信息
            order_info = self.order_parser.parse_order_info(order_folder)
            if not order_info:
                print(f"❌ 无法解析订单信息: {order_folder}")
                return
            
            number = order_info['number']
            customer = order_info['customer']
            
            print(f"📋 删除订单: {number} - {customer}")
            
            # 查找数据库中的订单
            order = self.db_manager.find_order_by_number(number)
            if order:
                # 删除数据库中的订单
                success = self.db_manager.delete_order(number)
                if success:
                    print(f"✅ 已从数据库删除订单: {number} - {customer}")
                    
                    # 通知状态变化（订单被删除）
                    status_data = {
                        'action': 'deleted',
                        'number': number,
                        'customer': customer,
                        'path': order_path,
                        'timestamp': time.time()
                    }
                    
                    # 通过队列通知状态变化
                    if self.callback_queue:
                        self.callback_queue.put(('order_deleted', number, status_data))
                else:
                    print(f"❌ 删除订单失败: {number} - {customer}")
            else:
                print(f"⚠️ 数据库中未找到订单: {number} - {customer}")
                
        except Exception as e:
            print(f"❌ 处理订单删除错误: {e}")
            import traceback
            traceback.print_exc()


class FileMonitorManager:
    """文件监控管理器"""
    
    def __init__(self, db_manager: DatabaseManager, order_parser: OrderParser):
        self.db_manager = db_manager
        self.order_parser = order_parser
        self.observers: Dict[str, Observer] = {}
        self.monitored_paths: Dict[str, str] = {}
        self.status_callbacks: List[Callable] = []
        
        # 从配置文件读取监控配置
        self.config = get_config()
        self.monitor_config = self.config.get_monitor_config()
        self.BASE_MONITOR_PATH = self.monitor_config['base_path']
        
        print(f"📁 监控目录配置: {self.BASE_MONITOR_PATH}")
        
        # 回调队列
        self.callback_queue = queue.Queue()
        self.queue_processor_running = False
    
    def add_status_callback(self, callback: Callable):
        """添加状态变化回调"""
        self.status_callbacks.append(callback)
    
    def remove_status_callback(self, callback: Callable):
        """移除状态变化回调"""
        if callback in self.status_callbacks:
            self.status_callbacks.remove(callback)
    
    def _notify_status_change(self, order_number: str, status_data: dict):
        """通知状态变化"""
        for callback in self.status_callbacks:
            try:
                # 检查是否是协程函数
                if asyncio.iscoroutinefunction(callback):
                    # 创建新的事件循环来运行异步回调
                    loop = asyncio.new_event_loop()
                    asyncio.set_event_loop(loop)
                    loop.run_until_complete(callback(order_number, status_data))
                    loop.close()
                else:
                    # 直接调用同步回调
                    callback(order_number, status_data)
            except Exception as e:
                print(f"状态变化回调错误: {e}")
    
    def start_queue_processor(self):
        """启动队列处理器"""
        if self.queue_processor_running:
            return
        
        self.queue_processor_running = True
        
        def process_queue():
            while self.queue_processor_running:
                try:
                    # 从队列获取事件
                    item = self.callback_queue.get(timeout=1.0)
                    if item:
                        # 处理不同类型的事件
                        if isinstance(item, tuple) and len(item) >= 3:
                            # 新格式：(event_type, order_number, status_data)
                            event_type = item[0]
                            order_number = item[1]
                            status_data = item[2]
                        elif isinstance(item, dict):
                            # 旧格式：字典
                            event_type = item.get('type', 'status_change')
                            order_number = item.get('order_number')
                            status_data = item.get('status_data')
                        else:
                            continue
                        
                        print(f"📨 处理事件: {event_type}, 订单编号: {order_number}")
                        
                        # 根据事件类型处理
                        if event_type == 'order_updated':
                            # 订单信息更新事件，需要特殊处理
                            print(f"🔄 处理订单信息更新: {order_number}")
                            # 这里可以添加特殊的订单更新处理逻辑
                            # 目前通过状态变化回调来处理
                            event_type = 'status_change'
                        
                        # 通知所有回调
                        for callback in self.status_callbacks:
                            try:
                                # 检查是否是协程函数
                                if asyncio.iscoroutinefunction(callback):
                                    # 创建新的事件循环来运行异步回调
                                    loop = asyncio.new_event_loop()
                                    asyncio.set_event_loop(loop)
                                    loop.run_until_complete(callback(order_number, status_data))
                                    loop.close()
                                else:
                                    # 直接调用同步回调
                                    callback(order_number, status_data)
                            except Exception as e:
                                print(f"队列回调错误: {e}")
                                
                except queue.Empty:
                    continue
                except Exception as e:
                    print(f"队列处理错误: {e}")
        
        # 启动队列处理线程
        thread = threading.Thread(target=process_queue)
        thread.daemon = True
        thread.start()
        print("✅ 队列处理器已启动")
    
    def stop_queue_processor(self):
        """停止队列处理器"""
        self.queue_processor_running = False
        print("✅ 队列处理器已停止")
    
    def get_today_monitor_path(self) -> str:
        """获取今天的监控路径"""
        today = datetime.now()
        # 格式化为 M.D 格式，例如 9.2
        date_str = f"{today.month}.{today.day}"
        return os.path.join(self.BASE_MONITOR_PATH, date_str)
    
    def start_automatic_monitoring(self) -> bool:
        """启动自动监控"""
        try:
            monitor_path = self.get_today_monitor_path()
            today = datetime.now()
            date_str = f"{today.month}.{today.day}"
            print(f"自动监控路径: {monitor_path}")
            
            if not os.path.exists(monitor_path):
                print(f"监控路径不存在，创建目录: {monitor_path}")
                os.makedirs(monitor_path, exist_ok=True)
            
            # 停止之前的监控
            if monitor_path in self.observers:
                self.stop_monitoring(monitor_path)
            
            # 创建新的观察者
            observer = Observer()
            event_handler = OrderFileHandler(
                monitor_path, 
                self.db_manager, 
                self.order_parser,
                self._notify_status_change,
                self.callback_queue
            )
            observer.schedule(event_handler, monitor_path, recursive=True)
            observer.start()
            
            self.observers[monitor_path] = observer
            self.monitored_paths[monitor_path] = date_str
            
            # 初始扫描
            self._initial_scan(monitor_path)
            
            print(f"✅ 自动监控已启动: {monitor_path}")
            return True
            
        except Exception as e:
            print(f"❌ 启动自动监控失败: {e}")
            return False
    
    def start_monitoring(self, base_path: str, date: str) -> bool:
        """开始文件监控"""
        try:
            full_path = os.path.join(base_path, date)
            
            if not os.path.exists(full_path):
                print(f"路径不存在: {full_path}")
                return False
            
            # 停止之前的监控
            if full_path in self.observers:
                self.stop_monitoring(full_path)
            
            # 创建新的观察者
            observer = Observer()
            event_handler = OrderFileHandler(
                full_path, 
                self.db_manager, 
                self.order_parser,
                self._notify_status_change,
                self.callback_queue
            )
            observer.schedule(event_handler, full_path, recursive=True)
            observer.start()
            
            self.observers[full_path] = observer
            self.monitored_paths[full_path] = date
            
            # 初始扫描
            self._initial_scan(full_path)
            
            print(f"✅ 监控已启动: {full_path}")
            return True
            
        except Exception as e:
            print(f"❌ 启动监控失败: {e}")
            return False
    
    def stop_monitoring(self, path: str = None) -> bool:
        """停止文件监控"""
        try:
            if path:
                # 停止指定路径的监控
                if path in self.observers:
                    self.observers[path].stop()
                    self.observers[path].join()
                    del self.observers[path]
                    if path in self.monitored_paths:
                        del self.monitored_paths[path]
                    print(f"✅ 监控已停止: {path}")
                    return True
                return False
            else:
                # 停止所有监控
                for observer in self.observers.values():
                    observer.stop()
                    observer.join()
                
                self.observers.clear()
                self.monitored_paths.clear()
                
                print("✅ 所有监控已停止")
                return True
                
        except Exception as e:
            print(f"❌ 停止监控失败: {e}")
            return False
    
    def _initial_scan(self, base_path: str):
        """初始扫描"""
        try:
            print(f"🔍 开始初始扫描: {base_path}")
            
            if not os.path.exists(base_path):
                print(f"❌ 监控路径不存在: {base_path}")
                return
            
            # 统计信息
            total_folders = 0
            order_folders = 0
            new_orders = 0
            updated_orders = 0
            
            # 扫描所有文件夹
            for item in os.listdir(base_path):
                item_path = os.path.join(base_path, item)
                total_folders += 1
                
                if os.path.isdir(item_path) and self.order_parser.is_order_folder(item):
                    order_folders += 1
                    print(f"📁 发现订单文件夹: {item}")
                    
                    # 处理订单文件夹
                    order_info = self.order_parser.parse_order_info(item)
                    if not order_info:
                        print(f"❌ 无法解析订单信息: {item}")
                        continue
                    
                    number, customer = order_info['number'], order_info['customer']
                    print(f"📋 订单信息: {number} - {customer}")
                    
                    # 检查订单是否存在
                    order = self.db_manager.find_order_by_number(number)
                    
                    if not order:
                        # 创建新订单
                        order_data = {
                            'number': number,
                            'customer': customer,
                            'path': item_path
                        }
                        order = self.db_manager.create_order(order_data)
                        new_orders += 1
                        print(f"🆕 创建新订单: {number} - {customer}")
                    else:
                        # 更新现有订单的路径和客户信息
                        update_data = {}
                        if order['path'] != item_path:
                            update_data['path'] = item_path
                        if order['customer'] != customer:
                            update_data['customer'] = customer
                        
                        if update_data:
                            self.db_manager.update_order(number, update_data)
                            print(f"🔄 更新订单信息: {number} - {customer}")
                            if 'path' in update_data:
                                print(f"  📁 路径已更新: {item_path}")
                            if 'customer' in update_data:
                                print(f"  👤 客户已更新: {customer}")
                            
                            # 发送订单信息更新通知
                            if self.callback_queue:
                                print(f"📡 发送订单信息更新通知: 订单编号 {number}")
                                self.callback_queue.put(('order_updated', number, update_data))
                    
                    # 自动创建状态文件夹（如果不存在）
                    self.order_parser.create_status_folders(item_path)
                    
                    # 检查状态（实时计算，不存储到数据库）
                    print(f"🔍 检查订单状态: {item_path}")
                    status_data = self.order_parser.check_order_status(item_path)
                    print(f"📊 状态数据: {status_data}")
                    
                    # 发送状态变化通知
                    if self.callback_queue:
                        print(f"📡 发送初始状态通知: 订单编号 {number}")
                        self.callback_queue.put(('status_change', number, status_data))
                    
                    updated_orders += 1
                    print(f"✅ 订单状态已检查: {number}")
                else:
                    print(f"📂 非订单文件夹: {item}")
            
            # 打印扫描结果
            print(f"\n📊 初始扫描完成:")
            print(f"  📁 总文件夹数: {total_folders}")
            print(f"  📋 订单文件夹数: {order_folders}")
            print(f"  🆕 新创建订单: {new_orders}")
            print(f"  🔄 更新订单: {updated_orders}")
            
            # 检查是否有订单需要清理（路径不存在）
            self._cleanup_missing_orders(base_path)
                    
        except Exception as e:
            print(f"❌ 初始扫描错误: {e}")
            import traceback
            traceback.print_exc()
    
    def _cleanup_missing_orders(self, base_path: str):
        """清理不存在的订单"""
        try:
            print(f"\n🧹 检查需要清理的订单...")
            
            # 获取所有订单
            all_orders = self.db_manager.get_all_orders()
            cleaned_count = 0
            
            for order in all_orders:
                order_path = order.get('path', '')
                if order_path and not os.path.exists(order_path):
                    print(f"🗑️ 订单路径不存在，删除数据库记录: {order['number']} - {order['customer']}")
                    # 删除数据库中的订单记录
                    success = self.db_manager.delete_order(order['number'])
                    if success:
                        cleaned_count += 1
                        print(f"✅ 已删除数据库记录: {order['number']} - {order['customer']}")
                        
                        # 通知删除事件
                        status_data = {
                            'action': 'deleted',
                            'number': order['number'],
                            'customer': order['customer'],
                            'path': order_path,
                            'timestamp': time.time()
                        }
                        
                        # 通过队列通知状态变化
                        if self.callback_queue:
                            self.callback_queue.put(('order_deleted', order['number'], status_data))
                    else:
                        print(f"❌ 删除数据库记录失败: {order['number']} - {order['customer']}")
            
            if cleaned_count > 0:
                print(f"✅ 清理了 {cleaned_count} 个无效订单")
            else:
                print(f"✅ 没有需要清理的订单")
                
        except Exception as e:
            print(f"❌ 清理订单时发生错误: {e}")
    
    def cleanup_all_missing_orders(self) -> dict:
        """清理所有不存在的订单"""
        try:
            print(f"🧹 开始清理所有无效订单...")
            
            # 获取所有订单
            all_orders = self.db_manager.get_all_orders()
            cleaned_count = 0
            errors = []
            
            print(f"📊 检查 {len(all_orders)} 个订单...")
            
            for order in all_orders:
                order_path = order.get('path', '')
                if order_path and not os.path.exists(order_path):
                    print(f"🗑️ 订单路径不存在: {order['number']} - {order['customer']} ({order_path})")
                    
                    try:
                        # 删除数据库中的订单记录
                        success = self.db_manager.delete_order(order['number'])
                        if success:
                            cleaned_count += 1
                            print(f"✅ 已删除数据库记录: {order['number']} - {order['customer']}")
                            
                            # 通知删除事件
                            status_data = {
                                'action': 'deleted',
                                'number': order['number'],
                                'customer': order['customer'],
                                'path': order_path,
                                'timestamp': time.time()
                            }
                            
                            # 通过队列通知状态变化
                            if self.callback_queue:
                                self.callback_queue.put(('order_deleted', order['number'], status_data))
                        else:
                            error_msg = f"删除数据库记录失败: {order['number']} - {order['customer']}"
                            print(f"❌ {error_msg}")
                            errors.append(error_msg)
                    except Exception as e:
                        error_msg = f"删除订单 {order['number']} 时出错: {e}"
                        print(f"❌ {error_msg}")
                        errors.append(error_msg)
            
            result = {
                'total_checked': len(all_orders),
                'cleaned_count': cleaned_count,
                'errors': errors
            }
            
            print(f"\n📊 清理完成:")
            print(f"  📋 检查订单数: {result['total_checked']}")
            print(f"  🗑️ 清理订单数: {result['cleaned_count']}")
            if result['errors']:
                print(f"  ❌ 错误数: {len(result['errors'])}")
                for error in result['errors']:
                    print(f"    - {error}")
            
            return result
            
        except Exception as e:
            print(f"❌ 清理所有无效订单失败: {e}")
            import traceback
            traceback.print_exc()
            return {'error': str(e)}
    
    def full_scan_current_date(self) -> dict:
        """全量扫描当前日期目录"""
        try:
            print(f"🔍 开始全量扫描，扫描当前日期目录")
            
            from datetime import datetime
            
            scan_results = {
                'total_dates_scanned': 0,
                'total_orders_found': 0,
                'new_orders_created': 0,
                'orders_updated': 0,
                'scanned_dates': [],
                'errors': []
            }
            
            # 只扫描当前日期
            today = datetime.now()
            date_str = f"{today.month}.{today.day}"
            scan_path = os.path.join(self.BASE_MONITOR_PATH, date_str)
            
            if os.path.exists(scan_path):
                print(f"\n📅 扫描当前日期目录: {date_str}")
                scan_results['scanned_dates'].append(date_str)
                scan_results['total_dates_scanned'] += 1
                
                # 执行扫描
                try:
                    self._initial_scan(scan_path)
                    scan_results['total_orders_found'] += 1
                except Exception as e:
                    error_msg = f"扫描 {date_str} 时出错: {e}"
                    print(f"❌ {error_msg}")
                    scan_results['errors'].append(error_msg)
            else:
                print(f"📂 当前日期目录不存在: {scan_path}")
                print(f"💡 提示: 当前日期目录 {date_str} 不存在，将创建该目录")
                
                # 创建当前日期目录
                try:
                    os.makedirs(scan_path, exist_ok=True)
                    print(f"✅ 已创建当前日期目录: {scan_path}")
                except Exception as e:
                    error_msg = f"创建目录 {scan_path} 时出错: {e}"
                    print(f"❌ {error_msg}")
                    scan_results['errors'].append(error_msg)
            
            # 打印扫描总结
            print(f"\n📊 全量扫描完成:")
            print(f"  📅 扫描日期数: {scan_results['total_dates_scanned']}")
            print(f"  📋 发现订单数: {scan_results['total_orders_found']}")
            print(f"  🆕 新创建订单: {scan_results['new_orders_created']}")
            print(f"  🔄 更新订单数: {scan_results['orders_updated']}")
            
            if scan_results['errors']:
                print(f"  ❌ 错误数: {len(scan_results['errors'])}")
                for error in scan_results['errors']:
                    print(f"    - {error}")
            
            return scan_results
            
        except Exception as e:
            print(f"❌ 全量扫描失败: {e}")
            import traceback
            traceback.print_exc()
            return {'error': str(e)}
    
    def get_monitoring_status(self) -> dict:
        """获取监控状态"""
        today = datetime.now()
        date_str = f"{today.month}.{today.day}"
        current_monitor_path = self.get_today_monitor_path()
        
        return {
            "base_monitor_path": self.BASE_MONITOR_PATH,
            "current_date": date_str,
            "current_monitor_path": current_monitor_path,
            "monitored_paths": list(self.monitored_paths.keys()),
            "is_monitoring": current_monitor_path in self.observers,
            "active_observers": len(self.observers)
        }
    
    def is_monitoring(self, path: str = None) -> bool:
        """检查是否正在监控"""
        if path:
            return path in self.observers
        return len(self.observers) > 0
    
    def get_monitored_paths(self) -> List[str]:
        """获取所有监控路径"""
        return list(self.monitored_paths.keys())
    
    def restart_monitoring(self) -> bool:
        """重启监控"""
        try:
            # 停止所有监控
            self.stop_monitoring()
            
            # 重新启动自动监控
            return self.start_automatic_monitoring()
        except Exception as e:
            print(f"重启监控失败: {e}")
            return False
